--[[
    使用方法：
    local myhttp = require("app.util.http_util")
    --get
    local resp, err = myhttp.http_get("http://zixuephp.net/index.html?name=test",3000)
    --post
    local body = {"name" = "test"}
    local resp, err = myhttp.http_post("http://zixuephp.net/index.html?name=test",body,3000)
--]]


local http = require("resty.http")
local myhttp = {}

--[[
    GET请求
--]]
function myhttp:http_get()
    local httpc = http.new()
    local res, err_ = httpc:request_uri("http://127.0.0.1:8888/topo/tags",{
        method = "GET",
        headers = {
          ["Content-Type"] = "application/x-www-form-urlencoded"
        },
        keepalive_timeout = 60,
        keepalive_pool = 10
    })
    -- if res.status == ngx.HTTP_OK then
    --     ngx.say(res.body)
    -- else
    --     ngx.exit(res.status)
    -- end
    return res.body, err_
end

--[[
    POST请求
--]]
function myhttp:http_post(url,body, timeout)
    local httpc = http.new()
    timeout = timeout or 30000
    httpc:set_timeout(timeout)
    local res, err_ = httpc:request_uri(url, {
        method = "POST",
        body = body,
        headers = {
            ["Content-Type"] = "application/json;charset=utf8",
        }
    })
    httpc:set_keepalive(5000, 100)
    httpc:close()
    if not res then
        return nil, err_
    else if res.status == 200 then
        return res.body, err_
    else
        return nil, err_ end
    end
end

function myhttp:https_post(url, body, timeout, ssl_verify)
    local httpc = http.new()
    timeout = timeout or 30000
    httpc:set_timeout(timeout)
    --ssl_verify
    --传参表示：用于客户端时要求服务器必须提供证书，用于服务器时服务器会发出证书请求消息要求客户端提供证书
    --不传参（false）表示：表示不验证
    local res, err_ = httpc:request_uri(url, {
            ssl_verify = ssl_verify or false,
            method = "POST",
            body = body,
            headers = {
                ["Content-Type"] = "application/json;charset=utf8",
            }
    })
    if not res then
        return nil, err_
    else
        if res.status == 200 then
            return res.body, err_
        else
            return nil, err_
        end
    end
end

return myhttp